<?php
/**
 * Created by PhpStorm.
 * User: ytl003
 * Date: 2018/10/12
 * Time: 上午12:55
 */

namespace app\api\controller;


use app\api\model\BookingModel;
use app\api\model\SiteModel;
use app\api\service\Back;
use app\api\service\TokenService;
use app\lib\exception\ErrorException;
use think\Db;
use think\Exception;
use think\facade\Request;
use think\helper\Time;

class Booking
{
    /**
     * @param int $site_id
     * @param string $choose_day
     * @return array
     * @throws \app\lib\exception\PermissionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @route('site/available')
     */
    public function siteAvailable($site_id = 0, $choose_day = '')
    {
        TokenService::needAllUserPermission();
        return Back::success(BookingModel::where('booking_day', strtotime($choose_day))
            ->where('status', 'in', [1, 2])->where('site_id', $site_id)
            ->hidden(['answer'])->select());
    }

    /**
     * @route('booking/save')
     */
    public function bookingSave()
    {
        $d = Request::param();
        $d['siteId'] = 9;
        $data = [
            'user_id' => TokenService::getCurrentUid(),
            'site_id' => $d['siteId'],
            'booking_day' => $d['yyTime'],
            'time_msg' => $d['chooseHour'],
            'answer' => json_encode($d['answer']),
            'annex' => json_encode($d['annex']),
            'status' => 1
        ];
        $booking = BookingModel::where('site_id', $d['siteId'])
            ->where('booking_day', strtotime($d['yyTime']))
            ->where('time_msg', $d['chooseHour'])->where('status', 'in', [1, 2])
            ->find();
        if ($booking)
            return Back::error('该时段已被预约');
        try {
            BookingModel::create($data);
            return Back::success('申请提交成功');
        } catch (Exception $e) {
            throw new ErrorException(['msg' => '程序错误，申请失败']);
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @route('my/booking')
     */
    public function getMyBooking($size = 5)
    {
        $userId = TokenService::getCurrentUid();
        return Back::success(BookingModel::with('site')->where('user_id', $userId)->order('update_time', 'desc')->paginate($size));
    }


    /**
     * @param int $bookingId
     * @return array
     * @throws ErrorException
     * @throws Exception\DbException
     * @route('booking/cancel')
     */
    public function cancelBooking($bookingId = 0){
        $userId = TokenService::getCurrentUid();
        $booking = BookingModel::get($bookingId);
        if ($booking['user_id'] != $userId)
            throw new ErrorException(['msg' => '您无此预约删除权限！']);
        Db::startTrans();
        try{
            $booking->status=4;
            $booking->save();
            Db::commit();
            return Back::success('ok');
        }catch (Exception $e){
            Db::rollback();
            throw new ErrorException(['msg' => '操作失败！请联系技术人员！']);
        }
    }

    /**
     * @param int $siteId
     * @param int $page
     * @return array
     * @throws ErrorException
     * @throws \think\exception\DbException
     * @route('booking/manege')
     */
    public function getMySiteBooking($siteId = 0, $size = 10,$status = 0)
    {

        $userId = TokenService::getCurrentUid();
        if($siteId == 0){
            $siteIds = SiteModel::where('admin_id',$userId)
                ->group('id')->column('id');
            if ($status !=0 ){
                return Back::success(BookingModel::with('site')
                    ->where('site_id','in',$siteIds)
                    ->where('status',$status)
                    ->order('create_time', 'desc')
                    ->paginate($size));
            }
            return Back::success(BookingModel::with('site')
                ->where('site_id','in',$siteIds)
                ->order('create_time', 'desc')
                ->paginate($size));
        }
        $site = SiteModel::get($siteId);
        if ($site['admin_id'] != $userId)
            throw new ErrorException(['msg' => '您无此场地管理权限！']);
        if ($status != 0){
            return Back::success(BookingModel::with('site')
                ->where('site_id',$siteId)
                ->where('status',$status)
                ->order('create_time', 'desc')
                ->paginate($size));
        }
        return Back::success(BookingModel::with('site')
            ->where('site_id',$siteId)
            ->order('create_time', 'desc')
            ->paginate($size));

    }


//    /**
//     * @param int $bookingId
//     * @return array
//     * @throws ErrorException
//     * @throws Exception\DbException
//     * @route('booking/detail')
//     */
//    public function getMyBookingDetails($bookingId = 0){
//        $userId = TokenService::getCurrentUid();
//        $booking = BookingModel::get($bookingId);
//        if ($booking['user_id'] != $userId)
//            throw new ErrorException(['msg' => '您无查看此预约权限']);
//        return Back::success($booking);
//    }

    /**
     * @param $bookingIds
     * @param string $action
     * @param string $msg
     * @return array
     * @throws ErrorException
     * @throws \app\lib\exception\PermissionException
     * @route('booking/handle')
     */
    public function handleBooking($bookingIds, $action = 'fail', $msg = '')
    {
        TokenService::needAdminPermission();
        TokenService::needWebPermission();
        if (!is_array($bookingIds))
            throw new ErrorException(['msg' => '操作失败！请联系技术人员！']);
        $ac = 1;
         if ($action == 'fail')
             $ac = 3;
         if ($action == 'success')
             $ac = 2;
         Db::startTrans();
         try{
             BookingModel::where('id','in',$bookingIds)->update([
                 'status' => $ac,
                 'reply' => $msg
             ]);
             Db::commit();
             return Back::success();
         }catch (Exception $e){
             Db::rollback();
             throw new ErrorException(['msg' => '操作失败！请联系技术人员！']);
         }
    }

}